using System;
using System.Data;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using mojoPortal.Business;
using mojoPortal.Business.Commerce;
using mojoPortal.Web;
using mojoPortal.Web.Controls.google;
using mojoPortal.Web.Framework;
using mojoPortal.Web.UI;
using eStore.Business;
using Resources;
using eStore.Helpers;
using log4net;
using System.Collections;

namespace eStore.UI
{
    public partial class OrderDetailPage : mojoBasePage
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(OrderDetailPage));
        protected int pageId = -1;
        protected int moduleId = -1;
        protected Store store;
        protected Guid orderGuid = Guid.Empty;
        protected Order order;
        protected SiteUser siteUser;
        protected Double timeOffset;
        protected CultureInfo currencyCulture;
        private DataSet dsProducts;
        private eStoreConfiguration config = new eStoreConfiguration();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (SiteUtils.SslIsAvailable()) { SiteUtils.ForceSsl(); }

            if (!UserCanViewPage(moduleId))
            {
                SiteUtils.RedirectToAccessDeniedPage();
                return;
            }

            LoadSettings();

            if (order == null)
            {
                WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());
                return;
            }

            if ((siteUser != null) && (order.UserGuid != siteUser.UserGuid))
            {
                SiteUtils.RedirectToAccessDeniedPage();
                return;
            }

            SetupCss();
            PopulateLabels();
            PopulateControls();
        }

        private void PopulateControls()
        {
            if (order == null) { return; }

            Title = SiteUtils.FormatPageTitle(siteSettings, " - " + eStoreResources.OrderDetailHeader + " - " + order.OrderGuid);
            lblOrderId.Text = order.OrderGuid.ToString();

            litOrderDate.Text = order.Completed.AddHours(timeOffset).ToShortDateString();
            litSubTotal.Text = StoreHelper.FormatPrice(order.SubTotal.ToString(), currencyCulture);
            litDiscount.Text = StoreHelper.FormatPrice(order.Discount.ToString(), currencyCulture);
            litShippingTotal.Text = StoreHelper.FormatPrice(order.ShippingTotal.ToString(), currencyCulture);
            litTaxTotal.Text = StoreHelper.FormatPrice(order.TaxTotal.ToString(), currencyCulture);
            litOrderTotal.Text = StoreHelper.FormatPrice(order.OrderTotal.ToString(), currencyCulture);

            pnlDiscount.Visible = (order.Discount > 0);
            pnlShippingTotal.Visible = (order.ShippingTotal > 0);
            pnlTaxTotal.Visible = (order.TaxTotal > 0);

            if ((order.ShippingTotal == 0) && (order.TaxTotal == 0) && (order.Discount == 0))
            {
                pnlSubTotal.Visible = false;
            }

            //using (IDataReader reader = order.GetProducts())
            //{
            //    rptOrderItems.DataSource = reader;
            //    rptOrderItems.DataBind();
            //}

            dsProducts = Order.GetOrderProductsAndProducts(store.Guid, orderGuid);
            rptProducts.DataSource = dsProducts;
            rptProducts.DataBind();
            // once payment has cleared, status will be fullfillable or fullfilled
            // pending payments are common for echeck or overseas accounts
            // lets not give them the ability to download until payment has cleared
            if (order.StatusGuid == OrderStatus.OrderStatusReceivedGuid)
            {
                litPaymentPending.Text = eStoreResources.PaymentPendingMessage;
            }

            PopulateCustomerInfo();
            DoGoogleAnalyticsTracking();

        }

        private void PopulateCustomerInfo()
        {
            if (order == null) { return; }
            if (siteUser == null && !config.UseEmailSystemOnlySetting) { return; }
            if (siteUser != null)
            {
                if (siteUser.UserGuid != order.UserGuid) { return; }
            }
            // don't show customer information in the page ifnot using ssl
            //if (!Request.IsSecureConnection) { return; }

            pnlCustomer.Visible = true;

            litBillingName.Text = order.BillingFirstName + @" " + order.BillingLastName;

            if (order.BillingCompany.Length > 0)
            {
                litBillingCompany.Text = order.BillingCompany;
            }

            litBillingAddress1.Text = order.BillingAddress1;

            litBillingCity.Text = order.BillingCity;
            litBillingState.Text = order.BillingState;
            litBillingPostalCode.Text = order.BillingPostalCode;
            litBillingCountry.Text = order.BillingCountry;
            litBillingEmail.Text = order.CustomerEmail;
            litBillingTelephoneDay.Text = order.CustomerTelephoneDay;
        }

        void rptProducts_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (dsProducts == null) { return; }

            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                string productGuid = ((DataRowView)e.Item.DataItem).Row.ItemArray[0].ToString();
                Repeater repeater = (Repeater)e.Item.FindControl("rptProducts");

                if (repeater == null) { return; }

                string whereClause = string.Format("ProductGuid = '{0}'", productGuid);
                DataView dv = new DataView(dsProducts.Tables["Products"], whereClause, "", DataViewRowState.CurrentRows);
                if (dv.Count > 1)
                {
                    repeater.DataSource = dv;
                    repeater.DataBind();
                }


            }
        }

        private void DoGoogleAnalyticsTracking()
        {
            if (order == null) { return; }
            if (order.AnalyticsTracked) { return; }
            if (store == null) { return; }

            try
            {
                if (Page.Master != null)
                {
                    mojoGoogleAnalyticsScript analytics = Page.Master.FindControl("mojoGoogleAnalyticsScript1") as mojoGoogleAnalyticsScript;
                    if (analytics == null) { DoAsyncTracking(); return; }

                    AnalyticsTransaction transaction = new AnalyticsTransaction
                                                           {
                                                               OrderId = order.OrderGuid.ToString(),
                                                               City = order.CustomerCity,
                                                               Country = order.CustomerCountry,
                                                               State = order.CustomerState,
                                                               StoreName = siteSettings.SiteName + " - " + store.Name,
                                                               Tax =
                                                                   order.TaxTotal.ToString(CultureInfo.InvariantCulture),
                                                               Total =
                                                                   order.OrderTotal.ToString(
                                                                       CultureInfo.InvariantCulture)
                                                           };

                    foreach (OrderProduct product in order.OrderProducts)
                    {
                        AnalyticsTransactionItem item = new AnalyticsTransactionItem
                                                            {
                                                                Category = string.Empty,
                                                                OrderId = order.OrderGuid.ToString(),
                                                                Price =
                                                                    product.ProductPrice.ToString(
                                                                        CultureInfo.InvariantCulture),
                                                                ProductName = product.Name,
                                                                Quantity =
                                                                    product.Quantity.ToString(
                                                                        CultureInfo.InvariantCulture),
                                                                Sku = product.ProductGuid.ToString()
                                                            };
                        transaction.Items.Add(item);

                    }

                    if (transaction.IsValid())
                    {
                        analytics.Transactions.Add(transaction);
                        Order.TrackAnalytics(order.OrderGuid);
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error("error tracking order in google analytics.", ex);
            }

        }

        private void DoAsyncTracking()
        {
            if (Page.Master == null) return;
            AnalyticsAsyncTopScript analytics = Page.Master.FindControl("analyticsTop") as AnalyticsAsyncTopScript;
            if (analytics == null) { return; }

            AnalyticsTransaction transaction = new AnalyticsTransaction
                                                   {
                                                       OrderId = order.OrderGuid.ToString(),
                                                       City = order.CustomerCity,
                                                       Country = order.CustomerCountry,
                                                       State = order.CustomerState,
                                                       StoreName = siteSettings.SiteName + " - " + store.Name,
                                                       Tax = order.TaxTotal.ToString(CultureInfo.InvariantCulture),
                                                       Total = order.OrderTotal.ToString(CultureInfo.InvariantCulture)
                                                   };

            foreach (OrderProduct product in order.OrderProducts)
            {
                AnalyticsTransactionItem item = new AnalyticsTransactionItem
                                                    {
                                                        Category = string.Empty,
                                                        OrderId = order.OrderGuid.ToString(),
                                                        Price =
                                                            product.ProductPrice.ToString(CultureInfo.InvariantCulture),
                                                        ProductName = product.Name,
                                                        Quantity =
                                                            product.Quantity.ToString(CultureInfo.InvariantCulture),
                                                        Sku = product.ProductGuid.ToString()
                                                    };
                transaction.Items.Add(item);

            }

            if (transaction.IsValid())
            {
                analytics.Transactions.Add(transaction);
                Order.TrackAnalytics(order.OrderGuid);
            }
        }


        private void PopulateLabels()
        {
            moduleTitle.Header = eStoreResources.OrderDetail;
            if (Master != null)
            {
                Control c = Master.FindControl("Breadcrumbs");
                if (c != null)
                {
                    BreadcrumbsControl crumbs = (BreadcrumbsControl)c;
                    crumbs.ForceShowBreadcrumbs = true;
                }
            }

            Title = SiteUtils.FormatPageTitle(siteSettings, eStoreResources.OrderDetailHeader);

            litOrderHeader.Text = eStoreResources.OrderDetailHeader;
            litItemsHeader.Text = eStoreResources.OrderDetailItemsHeader;
            litDownloadItemsHeader.Text = eStoreResources.OrderDetailDownloadItemsHeader;
            litBillingHeader.Text = eStoreResources.CheckoutBillingInfoHeader;
            btnFinish.Text = eStoreResources.FinishButtonLabel;
            btnFinish.PostBackUrl = SiteUtils.GetCurrentPageUrl();
            pnlOrderDetail.CssClass += " " + config.CustomCssClassSetting + "-cart";

        }

        private void LoadParams()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", moduleId);

        }

        private void LoadSettings()
        {
            timeOffset = SiteUtils.GetUserTimeOffset();
            if (Request.IsAuthenticated)
            {
                siteUser = SiteUtils.GetCurrentSiteUser();
            }

            if (CurrentPage.ContainsModule(moduleId))
            {
                store = StoreHelper.GetStore();
            }

            if (store == null) { return; }

            orderGuid = WebUtils.ParseGuidFromQueryString("orderid", orderGuid);
            if (orderGuid == Guid.Empty)
            {
                orderGuid = WebUtils.ParseGuidFromQueryString("order", orderGuid);

            }

            if (orderGuid != Guid.Empty)
            {
                order = new Order(orderGuid);
                if (order.StoreGuid != store.Guid) { order = null; return; }

                if ((order.StatusGuid == OrderStatus.OrderStatusCancelledGuid)
                    || (order.StatusGuid == OrderStatus.OrderStatusNoneGuid))
                { order = null; }

            }



        }

        protected virtual void SetupCss()
        {
            // older skins have this
            if (Page.Master == null) return;
            StyleSheet stylesheet = (StyleSheet)Page.Master.FindControl("StyleSheet");
            if (stylesheet == null) return;
            if (stylesheet.FindControl("styleestore") != null) return;
            Literal cssLink = new Literal
                                  {
                                      ID = "styleestore",
                                      Text = @"<link href='"
                                             + SiteUtils.GetSkinBaseUrl()
                                             + @"styleestore.css' type='text/css' rel='stylesheet' media='screen' />"
                                  };

            stylesheet.Controls.Add(cssLink);
        }


        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
        }

        protected override void OnInit(EventArgs e)
        {
            LoadParams();
            LoadPanels();
            base.OnInit(e);
            Load += Page_Load;
            rptProducts.ItemDataBound += rptProducts_ItemDataBound;

            SuppressPageMenu();

        }

        private void LoadPanels()
        {
            Hashtable settings = ModuleSettings.GetModuleSettings(moduleId);
            config = new eStoreConfiguration(settings);
            LoadSideContent(config.ShowLeftPanelSetting, config.ShowRightPanelSetting, config.ShowTopPanelSetting, config.ShowBottomPanelSetting, config.ShowCenterPanelSetting);
        }


        #endregion
    }
}
